<template>
  <el-dialog
    top="30px"
    width="900px"
    class="dialog-sm"
    append-to-body
    :before-close="beforeClose"
    :close-on-click-modal="false"
    :title="dialogTitle"
    :visible.sync="visible"
  >
    <el-form
      :model="editData"
      v-loading="loading"
      label-position="left"
      size="small"
      :rules="rules"
      ref="form"
      label-width="150px"
    >
      <h5 class="form-title">客户基础信息</h5>
      <el-form-item label="客户类型" prop="org_class">
        <c-select
          class="form-control-ml"
          v-model="editData.org_class"
          placeholder="客户类型"
          :options="enumCustomerType"
        ></c-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="customer_name">
        <el-input
          v-model="editData.customer_name"
          placeholder="客户名称"
          class="form-control-ml"
        ></el-input>
      </el-form-item>
      <el-form-item label="证件号" prop="lender_idcard">
        <el-input
          v-model="editData.lender_idcard"
          placeholder="证件号"
          class="form-control-ml"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="corp_phone">
        <el-input
          v-model="editData.corp_phone"
          class="form-control-ml"
          placeholder="请输入联系电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系地址" prop="address_code">
        <select-address
          class="form-control-ml"
          :top-value="'52'.padEnd(12, 0)"
          clearable
          v-model="editData.address_code"
        ></select-address>
      </el-form-item>
      <el-form-item label="详细地址(街道、门牌)">
        <el-input
          v-model="editData.address_detail"
          class="form-control-ml"
          placeholder="请勿重复输入已选地址（对已选地址的补充说明）"
        ></el-input>
      </el-form-item>

      <el-form-item label="所属行业" prop="industrial_code">
        <select-parent-main
          v-model="editData.industrial_code"
          @select="setParentMain"
          class="form-control-ml"
          placeholder="所属行业"
        ></select-parent-main>
      </el-form-item>

      <el-form-item label="销售收入">
        <el-input
          v-input-number="{ fixed: 6 }"
          v-model="editData.sale_income"
          placeholder="销售收入"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="资产总额">
        <el-input
          v-input-number="{ fixed: 6 }"
          v-model="editData.assets_total"
          placeholder="资产总额"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="从业人数">
        <el-input
          v-input-number="{ fixed: 0, min: 0 }"
          v-model="editData.emp_total"
          placeholder="从业人数"
          class="form-control-ml"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>
      <h5 class="form-title">婚姻信息</h5>
      <el-form-item label="婚姻状态">
        <c-select
          number-key
          v-model="editData.marriage_status"
          placeholder="婚姻状态"
          :options="enumMarriageStatus"
          class="form-control-ml"
        ></c-select>
      </el-form-item>
      <template v-if="editData.marriage_status === 1">
        <el-form-item label="配偶姓名" prop="spouse_name">
          <el-input
            v-model="editData.spouse_name"
            class="form-control-ml"
            placeholder="配偶姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="配偶证件号" prop="spouse_idcard">
          <el-input
            v-model="editData.spouse_idcard"
            placeholder="证件号"
            class="form-control-ml"
          ></el-input>
        </el-form-item>
        <el-form-item label="配偶联系电话" prop="spouse_phone">
          <el-input
            v-model="editData.spouse_phone"
            class="form-control-ml"
            placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>
      </template>
      <h5 class="form-title">授信借款信息</h5>
      <el-form-item label="授信金额" prop="reply_funds">
        <el-input
          v-input-number="{ fixed: 2, min: 0 }"
          v-model="editData.reply_funds"
          placeholder="授信金额"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="授信开始时间" prop="load_date_credit">
        <el-date-picker
          v-model="editData.load_date_credit"
          type="date"
          placeholder="授信开始时间"
          @change="countMountPeriod"
          class="form-control-ml"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="授信结束时间" prop="load_end_date_credit">
        <el-date-picker
          v-model="editData.load_end_date_credit"
          type="date"
          placeholder="授信结束时间"
          @change="countMountPeriod"
          class="form-control-ml"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="授信期限" prop="period_credit">
        <el-input
          v-input-number="{ fixed: 0, min: 0 }"
          v-model="editData.period_credit"
          disabled
          placeholder="授信期限"
          class="form-control-ml"
        >
          <span slot="append">月</span>
        </el-input>
      </el-form-item>
      <el-form-item label="授信/借款合同号" prop="gua_contract">
        <el-input
          v-model="editData.gua_contract"
          class="form-control-ml"
          placeholder="授信/借款合同号"
        ></el-input>
      </el-form-item>

      <el-form-item label="贷款金额" prop="warranty_amount">
        <el-input
          v-input-number="{ fixed: 6, min: 0 }"
          v-model="editData.warranty_amount"
          placeholder="贷款金额"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="贷款利率" prop="load_rate">
        <el-input
          v-input-number="{ fixed: 3, min: 0 }"
          v-model="editData.load_rate"
          placeholder="贷款利率"
          class="form-control-ml"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="贷款具体用途" prop="use_category">
        <select-funds-user
          v-model="editData.use_category"
          class="form-control-ml"
          :parent-id="editData.industrial_code"
          placeholder="贷款具体用途"
          @select="setFundsUse"
        ></select-funds-user>
      </el-form-item>
      <el-form-item label="贷款用途分类" prop="use_category_name">
        <c-select
          :props="{ value: 'label', label: 'label' }"
          v-model="editData.use_category_name"
          placeholder="贷款用途分类"
          :options="enumUseType"
          class="form-control-ml"
        ></c-select>
      </el-form-item>

      <h5 class="form-title">准入信息</h5>
      <el-form-item
        label-width="400px"
        label="年龄是否18-65周岁（借款人年龄加上贷款期限不超过65岁）"
        prop="is_age_65"
      >
        <el-switch
          v-model="editData.is_age_65"
          active-color="#67C23A"
          inactive-color="#F56C6C"
          :active-value="1"
          :active-text="editData.is_age_65 === 1 ? '是' : '否'"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item
        label-width="400px"
        label="本人或配偶，至少一人为当地人或在贷款申请所在地生活经营2年以上"
        prop="is_business_2"
      >
        <el-switch
          v-model="editData.is_business_2"
          active-color="#67C23A"
          inactive-color="#F56C6C"
          :active-value="1"
          :active-text="editData.is_business_2 === 1 ? '是' : '否'"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item
        label-width="400px"
        label="申请贷款日前两年内无连续五次逾期或累计八次逾期"
        prop="is_overdue_5"
      >
        <el-switch
          v-model="editData.is_overdue_5"
          active-color="#67C23A"
          inactive-color="#F56C6C"
          :active-value="1"
          :active-text="editData.is_overdue_5 === 1 ? '是' : '否'"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item
        label-width="400px"
        label="无重大法律纠纷（原告除外）及经济纠纷，未出现严重违法违规行为。"
        prop="is_crime"
      >
        <el-switch
          v-model="editData.is_crime"
          active-color="#67C23A"
          inactive-color="#F56C6C"
          :active-value="1"
          :active-text="editData.is_crime === 1 ? '是' : '否'"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>

      <h5 class="form-title">备注信息</h5>
      <el-form-item label="备注">
        <el-input
          v-model="editData.remark"
          type="textarea"
          rows="3"
          class="form-control-ml"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>

      <h5 class="form-title">银行AB角</h5>
      <el-form-item label="银行A角" prop="res_a">
        <select-staff
          v-model="editData.res_a"
          @select="setResAname"
          ref="resA"
          class="form-control-ml"
          :include-job="['business_manager']"
          placeholder="银行A角"
        ></select-staff>
      </el-form-item>
      <el-form-item label="银行B角" prop="res_b">
        <select-staff
          v-model="editData.res_b"
          @select="setResBname"
          ref="resA"
          class="form-control-ml"
          :include-job="['business_manager']"
          placeholder="银行B角"
        ></select-staff>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
          保存
        </el-button>
        <el-button :loading="saveLoading" class="btn-long" @click="beforeClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  enumCustomerType,
  enumMarriageStatus,
  enumUseType,
  countMonth,
} from '@/bank/views/business/hplimit/enum'
import { idCardValidator, mobileValidator } from '@/common/plugins/validator'
import SelectAddress from '@/components/select/SelectAddress'
import SelectParentMain from '@/bank/views/limit/SelectParentMain'
import { mapGetters } from 'vuex'
import { dateFormat } from '@/common/utils/common'
import SelectFundsUser from '@/bank/views/limit/SelectFundsUser'
import SelectStaff from '@/components/select/SelectStaff'
export default {
  components: {
    SelectAddress,
    SelectParentMain,
    SelectFundsUser,
    SelectStaff,
  },
  props: {
    visible: Boolean,
    tableId: String,
  },
  data() {
    return {
      enumCustomerType,
      enumMarriageStatus,
      enumUseType,
      loading: false,
      saveLoading: false,
      tableName: 'datum_one_county_industry',
      editData: {
        marriage_status: 1,
        period_credit: '',
        use_category: '',
        use_category_name: '',
        is_age_65: 1,
        is_business_2: 1,
        is_overdue_5: 1,
        is_crime: 1,
      },
      rules: {
        org_class: { required: true, message: '请选择客户类型', trigger: 'change' },
        customer_name: { required: true, message: '请输入客户名称', trigger: 'blur' },
        lender_idcard: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          {
            validator: idCardValidator,
            message: '请输入正确的身份证号码',
            trigger: 'blur',
          },
        ],
        industrial_code: { required: true, message: '请选择所属行业', trigger: 'change' },
        corp_phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '手机号码错误', trigger: 'blur' },
        ],
        address_code: { required: true, message: '请选择联系地址', trigger: 'change' },

        spouse_name: { required: true, message: '请输入配偶姓名', trigger: 'blur' },
        spouse_phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '手机号码错误', trigger: 'blur' },
        ],
        spouse_idcard: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          {
            validator: idCardValidator,
            message: '请输入正确的身份证号码',
            trigger: 'blur',
          },
        ],
        reply_funds: { required: true, message: '请输入授信金额', trigger: 'blur' },
        load_date_credit: { required: true, message: '请选择授信开始时间', trigger: 'change' },
        load_end_date_credit: [
          { required: true, message: '请选择授信结束时间', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (!value || !this.editData.load_date_credit) {
                callback()
              } else if (this.editData.load_date_credit > value) {
                callback(new Error('授信结束时间不能小于授信开始时间'))
              } else if (value < dateFormat(new Date())) {
                callback(new Error('授信结束时间不能小于当前日期'))
              } else {
                callback()
              }
            },
            trigger: 'change',
          },
        ],
        gua_contract: { required: true, message: '请输入授信/借款合同号', trigger: 'blur' },
        warranty_amount: { required: true, message: '请输入贷款金额', trigger: 'blur' },
        load_rate: { required: true, message: '请输入贷款利率', trigger: 'blur' },
        use_category: { required: true, message: '请选择贷款具体用途', trigger: 'change' },
        use_category_name: { required: true, message: '请选择贷款具体用途', trigger: 'change' },
        res_a: { required: true, message: '请选择项目A角', trigger: 'change' },
        res_b: { required: true, message: '请选择项目B角', trigger: 'change' },
      },
    }
  },
  computed: {
    ...mapGetters([
      'clientId',
      'org',
      'user',
      'userId',
      'provinceMainBusinessEnum',
      'industryType',
    ]),
    dialogTitle() {
      return this.tableId ? '修改项目信息' : '添加项目'
    },
    fundsUser() {
      return this.industryType.filter(item => +item.type === 3)
    },
    bankName() {
      return this.org.orgName
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    bankCode() {
      return this.org.orgCode
    },
  },
  watch: {
    tableId: {
      handler: function () {
        if (this.tableId) {
          this.getData()
        } else {
          this.editData = {
            marriage_status: 1,
            period_credit: '',
            use_category: '',
            use_category_name: '',
            is_age_65: 1,
            is_business_2: 1,
            is_overdue_5: 1,
            is_crime: 1,
          }
        }
      },
      immediate: true,
    },
  },
  created() {
    this.$store.dispatch('getProvinceMainBusiness')
    this.$store.dispatch('getIndustryType')
  },
  mounted() {},
  methods: {
    setFundsUse(select) {
      this.editData.funds_use_dir = select.value || ''
      this.editData.main_business_code = select.productTypeCode || this.editData.main_business_code
    },
    getData() {
      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, this.tableName, this.tableId)
        .then(res => {
          this.editData = res?.data ?? {}
          this.editData.marriage_status = +(this.editData.marriage_status || 1)
          this.editData.is_age_65 = +(this.editData.is_age_65 || 1)
          this.editData.is_business_2 = +(this.editData.is_business_2 || 1)
          this.editData.is_overdue_5 = +(this.editData.is_overdue_5 || 1)
          this.editData.is_crime = +(this.editData.is_crime || 1)
        })
        .finally(() => {
          this.loading = false
        })
    },
    setResAname(staff) {
      this.editData.res_a_name = staff.realName
    },
    setResBname(staff) {
      this.editData.res_b_name = staff.realName
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.onSubmit()
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    setParentMain(value, select) {
      const fundsUser = this.fundsUser.find(item => item.code === this.editData.use_category)
      if (!fundsUser || (value && fundsUser.parentId !== value)) {
        this.editData.use_category = this.editData.funds_use_dir || ''
      }
      this.$refs.form.validateField('use_category')
      this.editData.parent_main_business = select.value || ''
      this.editData.main_business_code = select.productTypeCode || ''
    },
    countMountPeriod() {
      this.editData.period_credit = countMonth(
        this.editData.load_date_credit,
        this.editData.load_end_date_credit
      )
    },
    onSubmit() {
      this.saveLoading = true
      if (this.tableId) {
        this.$api
          .updateData(this.$serviceName, this.tableName, this.tableId, this.editData)
          .then(() => {
            this.$message.success('修改成功！')
            this.beforeClose()
            this.$emit('success', true)
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .addData(this.$serviceName, this.tableName, {
            ...this.editData,
            warranty_rate: 0.4,
            is_gua_fee_customer: '0',
            claim_bank_name: this.bankName,
            address_name_county: '黄平县',
            address_name_city: '黔东南苗族侗族自治州',
            channel_type: 1,
            is_rural_dev: 2,
            submit_person_name: this.user.realName,
            bank_user_id: this.userId,
            bank_user_name: this.user.realName,
            bank_user_phone: this.user.phoneNumber,
            bank_id: this.clientId,
            corp_name: this.editData.customer_name,
            customer_type: 2,
            claim_status: 1,
            submit_type: 5,
            org_class_name: enumCustomerType[this.editData.org_class],
            main_business: this.provinceMainBusinessEnum[this.editData.main_business_code],

            bank_code: this.bankCode,
            bank_name: this.bankName,
            bank_type: this.bankType,
          })
          .then(() => {
            this.$message.success('添加成功！')
            this.beforeClose()
            this.$emit('success', true)
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleSuccess() {
      this.$emit('success', true)
    },
  },
}
</script>

<style lang="scss" scoped>
.form-title {
  font-size: 1.15rem;
  color: $gray-600;
  margin: 2rem 0 1rem 0;

  &:first-child {
    margin-top: 0;
  }
}
</style>
